from flask import request, jsonify, g
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity

from exts import db, run_sql_file
from models import User
from utils.password_utils import encode_password
from .predict_route import register_predict_routes
from .user_route import register_user_routes
from .dataset_route import register_dataset_routes
from .article_route import register_article_routes
from .auth_route import register_auth_routes
from .model_route import register_model_routes
from .plant_route import register_plant_routes
from .file_route import register_file_routes


# 路由配置
def register_all_routes(app):
    # 初始化数据库
    @app.before_request
    def initialize_data():
        if not app.config.get('INITIALIZED', False):
            # 运行 table.sql 文件
            run_sql_file('sql/table.sql')

            # 运行 data.sql 文件
            # run_sql_file('sql/data.sql')

            # 检查管理员用户是否已存在
            # 如果管理员用户已存在，跳过创建
            existing_admin = User.query.filter_by(name='admin').first()
            if not existing_admin:
                # 创建管理员用户
                hashed_password = encode_password('123456')
                new_super_admin = User(name='admin', password=hashed_password, role='admin')
                db.session.add(new_super_admin)
                db.session.commit()
            # else:
            #     print('超级管理员用户已存在，跳过创建')

            # 标记为已初始化
            app.config['INITIALIZED'] = True
        else:
            # 已经初始化，跳过
            # print('数据库已初始化，跳过')
            return

    # 全局拦截器，无token无法访问
    @app.before_request
    def route_interceptor():
        excluded_paths = ['/plantACR/login',
                          '/plantACR/createUser',
                          '/stream',
                          '/test',
                          '/']  # 需要排除的路径
        # 需要排除的路径前缀，不使用时注解掉即可，否则拦截器失效
        # excluded_start_paths = ['']
        # 不拦截 excluded_paths 集合中的请求
        if request.path in excluded_paths:
            return
        # 不拦截以 excluded_start_paths 开头的请求
        # for prefix in excluded_start_paths:
        #     if request.path.startswith(prefix):
        #         return
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            verify_jwt_in_request()  # JWT token验证
            tokeninfo = get_jwt_identity()  # 解析token
            # 往全局对象g中注入id和role
            g.id = tokeninfo.get('id')
            g.role = tokeninfo.get('role')
            print("用户UID：", g.id)
            print("用户角色：", g.role)
            print("请求路径：", request.path)
            print("请求方法：", request.method)
            print("Content-Type：", request.content_type)  # 新增请求头打印
        except Exception as e:
            resultVO["code"] = 401
            resultVO["message"] = "Token验证失败：" + str(e)
            return jsonify(resultVO)

    # SSE响应头设置
    @app.after_request
    def set_content_type(response):
        # 仅对SSE端点设置特殊头
        if request.path.startswith('/stream'):
            response.headers['Content-Type'] = 'text/event-stream'
            response.headers['Cache-Control'] = 'no-cache'
            response.headers['Connection'] = 'keep-alive'
        return response

    @app.route('/')
    def index():
        return 'Hello Flask!!!'

    app = register_auth_routes(app) # 登录鉴权
    app = register_user_routes(app) # 用户管理
    app = register_plant_routes(app) # 植物管理
    app = register_dataset_routes(app) # 数据集管理
    app = register_model_routes(app) # 模型管理
    app = register_predict_routes(app) # 预测管理
    app = register_file_routes(app) # 文件相关
    app = register_article_routes(app) # 文章管理

    return app
